package com.atguigu.tingshu.dispatch.job;

import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.dispatch.mapper.XxlJobLogMapper;
import com.atguigu.tingshu.model.dispatch.XxlJobLog;
import com.atguigu.tingshu.search.client.SearchFeignClient;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class DispatchJobHandler {

    @Autowired
    private SearchFeignClient searchFeignClient;

    @Autowired
    private XxlJobLogMapper xxlJobLogMapper;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    //  xxl-job 与业务整合
    //  1.  更新排行榜：
    @XxlJob("updateLatelyAlbumRankingJob")
    public Result updateLatelyAlbumRankingJob(){
        //  获取到方法执行的开始时间
        long startTime = System.currentTimeMillis();
        //  声明对象；记录系统日志
        XxlJobLog xxlJobLog = new XxlJobLog();
        xxlJobLog.setJobId(XxlJobHelper.getJobId());
        try {
            //  远程调用：
            searchFeignClient.updateLatelyAlbumRanking();
            //  表示执行成功
            xxlJobLog.setStatus(1);
        } catch (Exception e) {
            //  表示执行失败
            xxlJobLog.setStatus(0);
            //  记录error信息
            xxlJobLog.setError(e.getMessage());
        }
        //  获取到运行时间
        Integer times = Math.toIntExact(System.currentTimeMillis() - startTime);
        xxlJobLog.setTimes(times);
        //  保存日志记录信息。
        xxlJobLogMapper.insert(xxlJobLog);
        //  返回数据
        return Result.ok();
    }

    /**
     * 更新过期vip
     * @return
     */
    @XxlJob("updateVipExpireStatusJob")
    public Result updateVipExpireStatus(){
        //  获取到方法执行的开始时间
        long startTime = System.currentTimeMillis();
        //  声明对象；记录系统日志
        XxlJobLog xxlJobLog = new XxlJobLog();
        xxlJobLog.setJobId(XxlJobHelper.getJobId());
        try {
            //  远程调用：
            userInfoFeignClient.updateVipExpireStatus();
            //  表示执行成功
            xxlJobLog.setStatus(1);
        } catch (Exception e) {
            //  表示执行失败
            xxlJobLog.setStatus(0);
            //  记录error信息
            xxlJobLog.setError(e.getMessage());
        }
        //  获取到运行时间
        Integer times = Math.toIntExact(System.currentTimeMillis() - startTime);
        xxlJobLog.setTimes(times);
        //  保存日志记录信息。
        xxlJobLogMapper.insert(xxlJobLog);
        //  返回数据
        return Result.ok();
    }


    //  测试案例
    @XxlJob("testJob")
    public Result testJob(){
        //  打印输出.
        System.out.println("定时任务调度中心....");
        return Result.ok();
    }


}